/**
 * 
 */
package com.cipe.cmrs.controllers.payment;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.cipe.cmrs.bean.PaymentRequestBean;

/**
 * @author Incepio
 * 
 */
@Controller
@RequestMapping("/secure/processPaymentrequest.do")
public class ProcessPaymentController extends AbstractPaymentController {

    /**
	 * 
	 */
    private static final long serialVersionUID = 6120124465945710328L;

    private static final String FORM_VIEW = "payment/processPaymentrequest";

    @ModelAttribute(COMMAND_NAME)
    public PaymentRequestBean getCommand(@RequestParam Integer id) {
        return paymentrequestService.getPaymentRequestbean(id);
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getFormView(@ModelAttribute(COMMAND_NAME) PaymentRequestBean bean, HttpServletRequest request) {
        return new ModelAndView(FORM_VIEW).addAllObjects(getReferenceData(bean, request)).addAllObjects(getReferenceData(bean));
    }

    public ModelAndView getSuccessView(PaymentRequestBean bean, HttpServletRequest request) {
        return getFormView(bean, request);
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) PaymentRequestBean bean, BindingResult result,
        HttpServletRequest request, SessionStatus status) {
        ModelAndView mav = null;
        validator.validate(result, bean);
        if (result.hasErrors()) {
            mav = getFormView(bean, request);
            mav.addAllObjects(result.getModel());
            saveError(request, result.getGlobalErrors());
        } else {
            try {
                String nextAction = request.getParameter(getText("name.button.nextaction"));
                Map<String, Object> addlRefData = new HashMap<String, Object>();
                if (StringUtils.hasText(nextAction)) {
                    if (nextAction.equalsIgnoreCase(getText("editPaymentrequest.label.prCancel"))) {
                        // Commented due to BLOG101
                        /*
                        bean = paymentrequestService.cancelPaymentRequest(bean, getUserId(request),
                            getText("status.responsible.payment.process.financeassistant"));
                        */
                        addlRefData.put("nextButtonValue", getText("value.button.nextaction.processpayment"));
                        addlRefData.put("disableNextButtonValue", true);
                    } else if (nextAction.equalsIgnoreCase(getText("name.button.continuepaymentrequest"))) {
                        bean = paymentrequestService.forwardToFinance(bean, getUserId(request));
                    } else {
                        bean = paymentrequestService.processPaymentRequest(bean, getUserId(request));
                    }
                } else {
                    String action = request.getParameter("action");
                    if (getText("editPaymentrequest.label.cancel").equalsIgnoreCase(action)) {
                        bean = paymentrequestService.cancelPaymentRequest(bean, getUserId(request), null);
                    } else if (getText("editPaymentrequest.label.reject").equalsIgnoreCase(action)) {
                        bean = paymentrequestService.rejectPaymentRequest(bean, getUserId(request));
                    } else {
                        bean = paymentrequestService.savePaymentrequest(bean, getUserId(request));
                    }
                }
                saveMessage(request, getText("editPaymentrequest.message.success"));
                mav = getFormView(bean, request).addObject(COMMAND_NAME, bean).addAllObjects(addlRefData);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(getText("error.transaction"), e);
                saveError(request, getText("error.transaction"));
            }
        }
        return mav;
    }

    private Map<String, Object> getReferenceData(PaymentRequestBean bean) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("canCancelStatus", isCanCancelStatus(bean));
        map.put("canRejectStatus", isCanRejectStatus(bean));
        map.put("nextButtonValue", getNextButtonValue(bean));
		// By Andy: BLOG207 - User should be able to edit the record (ON THE
		// PAYMENT REQUEST - PROCESSING FORM ONLY) in any status EXCEPT "Paid"
		// or "Cancelled"
        boolean canEdit = !getText("status.payment.process.paid").equals(bean.getStatusCode())
            && !getText("status.payment.process.cancelled").equals(bean.getStatusCode());
        map.put("canEdit", canEdit);
        return map;
    }

    private boolean isCanCancelStatus(PaymentRequestBean bean) {
        return getText("status.payment.process.new").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.finance").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.cancelrequested").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.rejected").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.resubmitted").equalsIgnoreCase(bean.getStatusCode());

    }

    private boolean isCanRejectStatus(PaymentRequestBean bean) {
        return getText("status.payment.process.new").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.finance").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.signature").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.resubmitted").equalsIgnoreCase(bean.getStatusCode());
    }

    private String getNextButtonValue(PaymentRequestBean bean) {
        String retVal = null;
        if (getText("status.payment.process.new").equalsIgnoreCase(bean.getStatusCode())
            || getText("status.payment.process.resubmitted").equalsIgnoreCase(bean.getStatusCode())) {
            retVal = getText("value.button.nextaction.finance");
        } else if (getText("status.payment.process.finance").equalsIgnoreCase(bean.getStatusCode())) {
            retVal = getText("value.button.nextaction.signature");
        } else if (getText("status.payment.process.signature").equalsIgnoreCase(bean.getStatusCode())) {
            retVal = getText("value.button.nextaction.payment");
        } else if (getText("status.payment.process.pendingpayment").equalsIgnoreCase(bean.getStatusCode())) {
            retVal = getText("value.button.nextaction.paid");
        } else if (getText("status.payment.process.cancelrequested").equals(bean.getStatusCode())) {
            retVal = getText("value.button.nextaction.processpayment");
        }
        return retVal;
    }
}
